//#include "StdAfx.h"
#include <Windows.h>
#include <WinInet.h>
#include <Sensapi.h>
#include <tchar.h>
#include "HttpHelper.h"
#pragma comment(lib,"WinInet.lib")
#pragma comment(lib,"Sensapi.lib")
using namespace CODEHELPER;

CHttpHelper::CHttpHelper( void )
{
}


CHttpHelper::~CHttpHelper( void )
{
}


BOOL CHttpHelper::ParseURL( LPCTSTR pwszURL, LPTSTR pwszHostName, LPTSTR pwszPath, WORD& wPort )
{
    if ( pwszURL == NULL )
    {
        return FALSE;
    }

    WCHAR wszCanonicalizedURL[INTERNET_MAX_URL_LENGTH];
    int iLen = 0;
    BOOL bOk = EncodeURL( pwszURL, wcslen( pwszURL ), wszCanonicalizedURL, iLen );

    if ( bOk )
    {
        URL_COMPONENTS urlComponents = {0};
        urlComponents.dwStructSize = sizeof( URL_COMPONENTS );
        urlComponents.dwHostNameLength = INTERNET_MAX_URL_LENGTH;
        urlComponents.lpszHostName = pwszHostName;
        urlComponents.dwUrlPathLength = INTERNET_MAX_URL_LENGTH;
        urlComponents.lpszUrlPath = pwszPath;
        bOk = InternetCrackUrl( wszCanonicalizedURL, 0, ICU_ESCAPE, &urlComponents );
        bOk = ( bOk && urlComponents.nScheme == INTERNET_SERVICE_HTTP );

        if ( bOk )
        {
            wPort = urlComponents.nPort;
        }
    }

    return bOk;
}


BOOL CHttpHelper::EncodeURL( LPCTSTR pwszURL, int iLen, LPTSTR pwszRetURL, int& iRetLen )
{
    const WCHAR HEX_MAP[] =
    {
        _T( '0' ), _T( '1' ), _T( '2' ), _T( '3' ), _T( '4' ), _T( '5' ), _T( '6' ), _T( '7' ),
        _T( '8' ), _T( '9' ), _T( 'A' ), _T( 'B' ), _T( 'C' ), _T( 'D' ), _T( 'E' ), _T( 'F' )
    };

    char* pszBuff  = new char[iLen * 4];

    if ( pszBuff == NULL )
    {
        return FALSE;
    }

    int iCnt = WideCharToMultiByte( CP_UTF8, 0, pwszURL, iLen, pszBuff, iLen * 4, NULL, NULL );
    iRetLen = 0;

    for ( int i = 0; i < iCnt; i++ )
    {
        char ch = pszBuff[i];

        if ( ch > _T( ' ' ) && ch != _T( '%' ) )
        {
            pwszRetURL[iRetLen++] = ch;
        }
        else
        {
            int iVal = ch;
            pwszRetURL[iRetLen++] = _T( '%' );
            pwszRetURL[iRetLen++] = HEX_MAP[( iVal >> 4 ) & 0x0f];
            pwszRetURL[iRetLen++] = HEX_MAP[iVal & 0xf];
        }
    }

    pwszRetURL[iRetLen] = _T( '\0' );

    delete [] pszBuff;
    return TRUE;
}


HRESULT CHttpHelper::OpenUrlWithDefaultBrowser( LPCTSTR lpUrl )
{
    HRESULT hr = S_OK;
// 	HKEY hkRoot,hSubKey;
// 	TCHAR ValueName[256];
// 	TCHAR DataValue[256];
// 	unsigned long cbValueName=256;
// 	unsigned long cbDataValue=256;
// 	TCHAR ShellChar[256];
// 	DWORD dwType;
// 	CString str = _T("\"");
//
// 	if(RegOpenKey(HKEY_CLASSES_ROOT,NULL,&hkRoot)!=ERROR_SUCCESS)
// 	{
// 		return S_FALSE;
// 	}
// 	if (RegOpenKeyEx(hkRoot,_T("htmlfile\\shell\\open\\command"),0,KEY_READ,&hSubKey)!=ERROR_SUCCESS)
// 	{
// 		return S_FALSE;
// 	}
// 	RegEnumValue(hSubKey,0,ValueName,&cbValueName,NULL,&dwType,(LPBYTE)DataValue,&cbDataValue);
// 	lstrcpy(ShellChar,(TCHAR *)DataValue);
// 	TCHAR * pTemp=ShellChar;
// 	++pTemp;
// 	while(*pTemp != _T('"'))
// 	{
// 		str+=*pTemp;
// 		++pTemp;
// 	}
// 	str+=_T("\"");
// 	ShellExecute(NULL,_T("open"),str.GetBuffer(),lpUrl,NULL,SW_NORMAL);
// 	str.ReleaseBuffer();
//
// 	RegCloseKey(hSubKey);
// 	RegCloseKey(hkRoot);
    return hr;
}

BOOL CHttpHelper::IsHasNetConnect()
{
    DWORD dwFlag = 0;

    if ( !IsNetworkAlive( &dwFlag ) )
    {
        DWORD dwErr =::GetLastError();

        if ( 0 == dwErr )
        {
            return FALSE;
        }

        dwFlag = 0;

        if ( InternetGetConnectedState( &dwFlag, 0 ) )
        {
            if ( INTERNET_CONNECTION_OFFLINE == dwFlag )
            {
                return FALSE;
            }
        }
    }

    return TRUE;
}

BOOL CHttpHelper::OpenUrlWithIE( LPCTSTR lpszURL )
{
    typedef HINSTANCE( *ShellExecuteFunc )( HWND, LPCTSTR , LPCTSTR , LPCTSTR , LPCTSTR , int );
    ShellExecuteFunc mShellExecuteW = NULL;

    try
    {
        HINSTANCE hShell32 =::LoadLibrary( _T( "Shell32.dll" ) );

        if ( NULL != hShell32 )
        {
            mShellExecuteW = ( ShellExecuteFunc )::GetProcAddress( hShell32, "ShellExecuteA" );

            if ( NULL != mShellExecuteW )
            {
                HINSTANCE hins = mShellExecuteW( NULL, _T( "open" ), _T( "iexplore" ), lpszURL, NULL, SW_SHOWNORMAL );

                if ( 32 < reinterpret_cast<int>( hins ) )
                {
                    ::FreeLibrary( hShell32 );
                    return TRUE;
                }
            }

            ::FreeLibrary( hShell32 );
        }
    }
    catch ( ... )
    {
        return FALSE;
    }

    return FALSE;
}
